const linkTreeDirective = function ($timeout) {
    return {
        template: '<ul id="{{options.treeId}}" class="ztree"></ul>',
        scope:{
            options: '=',
            checkedNodeMap: '='
        },
        replace: true,
        link: function (scope, element, attr) {
            console.log(scope, attr, element)
            var treeObj = {
                treeId: scope.options.treeId,
                zTree: null,
                setting: {
                    data: {
                        simpleData: {
                            enable: true
                        }
                    },
                    callback:{
                        beforeClick: function (treeId, treeNode, clickFlag) {
                            console.log(treeId, treeNode, clickFlag);
                            // return false; 则不会触发onclick事件
                            return treeNode.click !=false
                        },
                        onClick: function (event, treeId, treeNode) {
                            console.log(event, treeId, treeNode);
                            if(scope.options.clickFun){
                                scope.options.clickFun(treeNode);
                            }
                        },
                        onCheck: function(event, treeId, treeNode){
                            scope.options.checkedNodeMap[treeNode.id] = treeNode.checked
                            $timeout(function(){
                                scope.$apply();
                            })
                        }
                    }
                },
                init: function () {
                    Object.assign(this.setting, scope.options.setting);
                    this.renderTree();
                },
                renderTree: function(){
                    this.zTree = $.fn.zTree.init($('#'+treeObj.treeId), this.setting, scope.options.zNodes);
                }
            }
            $timeout(()=>{
                treeObj.init();
            })
            var zTreeWatchFun = scope.$watch('options.zNodes',function(newVal, oldVal){
                if(newVal!==oldVal){
                    treeObj.init()
                }
            });
            scope.$on('$destroy',function(){
                console.log('destroy')
                zTreeWatchFun();
            });
        }
    }
};

export default ngModule => {
    ngModule.directive('linkTree', linkTreeDirective);
}